package com.easyfun.healthmagicbox;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.PersonProfileDownloadTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.pojo.UserToPersons;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.util.ImageTools;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.easyfun.healthmagicbox.widget.ProfileImageView;






import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 *  
 * @author tedyyan
 * 
 */
public class ImageAdapter extends BaseAdapter implements DatabaseAccess{
	// private Integer[] mImageIds = { R.drawable.one, R.drawable.two,
	// R.drawable.three };
	private List<ProfileImageView> pimageList = new ArrayList<ProfileImageView> ();
	private Context mContext;
	private String LOGTAG = ImageAdapter.class.getSimpleName();
	private boolean refreshFlag  = false;
	private static ImageAdapter instance = null;
	
	public static ImageAdapter getInstance(Context context)
	{
		//why this? so comment out
		//if (!(context instanceof HMBMainActivity))
		//{
		//	return null;
		//}
			
		if (instance == null)
		{
			instance = new ImageAdapter(context);
		}
		return instance;
	}
	
	private ImageAdapter(Context context) {
		this.mContext = context;
	}


	@Override
	public int getCount() {
		//load data dynamically
		if (pimageList.size() == 0)
			loadData(true);
		Log.i(LOGTAG, "getCount: "+pimageList.size()+1);
		//add dummy head for adding new person		
		return pimageList.size();
	}


	@Override
	public Object getItem(int position) {
		return position;
	}


	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ProfileImageView itemInGrid = null;
		
		//if (convertView == null) {
			if (position>=pimageList.size())
			{			
				Log.e(LOGTAG ,"head file name is null");	
			}else
			{
				itemInGrid = pimageList.get(position);
		        convertView = itemInGrid;  
				
			}
	        
			return itemInGrid ;
		//} else {
		//	return convertView;
		//} //

		
	}

	public void refresh()
	{
		refreshFlag = true;
	}
	public void loadData(boolean forceRefresh) {
		try {
			
			
			Dao<UserToPersons, Integer> utopDao = getHelper(this.mContext).getUserToPersonsDao();
			List<UserToPersons> utopresult = utopDao.queryBuilder()
					.orderBy("serverID", true).where()
					.eq("username", PersonProfileCache.getInstance(mContext).getUsername(mContext)).query();
			
			if (!forceRefresh)
			{
				//if no data to show means error
				//if count is same means no change.
				if (!refreshFlag)
				{	
					if ((utopresult.size()==0)||(utopresult.size()+1 == pimageList.size()))
					{
						if (utopresult.size()==0)
							Log.e(LOGTAG, "user has no profiles:"+PersonProfileCache.getInstance(mContext).getUsername(mContext));
						return;
						
					}
				}
			}
			//prevent always refresh.
			refreshFlag = false;

			Dao<PersonProfile, Integer> profileDao = getHelper(this.mContext).getPersonProfileDao();
			List<PersonProfile> allpeople = new ArrayList<PersonProfile>();
			
			for (ProfileImageView piv:pimageList)
			{
				Drawable[] oldbitmaps = piv.getCompoundDrawables();
				for (Drawable d:oldbitmaps)
				{
					if (d != null)
					{
						if ( d instanceof LayerDrawable ) {
							Drawable ld = ((LayerDrawable) d).getDrawable(0);
					        if ((ld != null) && (ld instanceof BitmapDrawable))
					        {
					        	//((BitmapDrawable)ld).getBitmap().recycle();
					        }	
					        Drawable ld2 = ((LayerDrawable) d).getDrawable(1);
					        if ((ld2 != null) && (ld2 instanceof BitmapDrawable))
					        {
					        	//((BitmapDrawable)ld2).getBitmap().recycle();
					        }
					    }
					}
				}				
			}
			pimageList.clear();
			
			for (UserToPersons up:utopresult)
			{
				List<PersonProfile> tmp = profileDao.queryForEq(
					"personID", up.getPersonID());
				//if no person found, fill in a dummy place holder.
				if ((tmp==null)||(tmp.size()==0))
				{
					PersonProfile dummy = new PersonProfile();
					dummy.setAge(0);
					//dummy.setTitle("下载中ing");
					dummy.setPersonID(ConstantData.DOWNLOADING_PERSON);
					dummy.setImageFileName(ConstantData.DEFAULT_HEAD_ICON_MALE);
					allpeople.add(dummy);
				}else
				{
					allpeople.addAll(tmp);
				}
				PersonProfileDownloadTask ppd = new PersonProfileDownloadTask(
						up.getPersonID(), mContext, new BasicCommCallback());
				HealthThreadPool.getInstance().execute(ppd);
			}
			Bitmap bitmap = null;
			ProfileImageView itemInGrid = null;
			for (PersonProfile p : allpeople) {
				//if no pic, send title and name for generating a picture
				View v = LayoutInflater.from(mContext).inflate(R.layout.gridview_item, null);  

				itemInGrid = (ProfileImageView) v.findViewById(R.id.itemInGrid); 
				
				Dao<UserToPersons, Integer> u2pDao = getHelper(this.mContext).getUserToPersonsDao();
				List<UserToPersons> u2ps = u2pDao.queryBuilder().where().eq("personID", p.getPersonID())
						.and().eq("username", PersonProfileCache.getInstance(mContext).getUsername(mContext)).query();
				if (u2ps.size() == 1)
				{
					itemInGrid.setTitle(u2ps.get(0).getRetitle());
				}else
				{
					itemInGrid.setTitle("下载中ing");
				}
				itemInGrid.setPersonid(p.getPersonID());
				itemInGrid.setImagefilename(p.getImageFileName());
				
				bitmap = URIConverter.getHeadFromAppSDCard(mContext, itemInGrid.getImagefilename(),p.getPersonID(),p.getSex());
				
				Drawable pic = null;
				//setting the corner icon
				if (p.getPersonID().equals(PersonProfileCache.getInstance(mContext).getPersonID(mContext)))
				{
					pic = ImageTools.addCornIcon(bitmap, R.drawable.head_sz, mContext.getResources());					
				}else
				{
					pic = ImageTools.addCornIcon(bitmap, R.drawable.head_xq, mContext.getResources());
				}
				
				pic.setBounds(0, 0, 200, 200); //pic.getMinimumWidth(),pic.getMinimumHeight());
				itemInGrid.setCompoundDrawables(null,
						pic,null,null);
				
				
				String title = itemInGrid.getTitle();
				if (title == null)
				{
					title="未设置";
				}else if (title.length() == 0)
				{
					title="邀请中..";
				}else if (title.equals("null"))
				{
					title="未设置";
				}
				itemInGrid.setText(title);
				
				//ProfileImageView pi = new ProfileImageView(mContext,p.getPersonID(),p.getImageFileName(),
				//			p.getTitle());
				
				pimageList.add(itemInGrid);
			}
			
			//for adding a new profile
			View v = LayoutInflater.from(mContext).inflate(R.layout.gridview_item, null);  
			itemInGrid = (ProfileImageView) v.findViewById(R.id.itemInGrid);  		
			itemInGrid.setTitle("?");
			itemInGrid.setPersonid(ConstantData.ADD_PERSON);
			itemInGrid.setImagefilename(ConstantData.nopicFileName);
			bitmap = URIConverter.getBitmapFromResources(mContext,R.drawable.bighead);
			
//			ImageView imageView = new ImageView(mContext);
//			imageView.setLayoutParams(new GridView.LayoutParams(200, 200));			
//			imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);					
//			imageView.setImageBitmap(bitmap);		
			
			Drawable pic = ImageTools.addCornIcon(bitmap, R.drawable.head_bj, mContext.getResources());
			
			pic.setBounds(0, 0, 200, 200);
			itemInGrid.setCompoundDrawables(null,
					pic,null,null);
			itemInGrid.setText("?");
			pimageList.add(itemInGrid);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
	
}

